#include "windows.h"
#include "winbase.h"
#include <process.h>
#include <iostream>
#include <tchar.h>

using namespace std;

class Singleton
{
private:
	Singleton()
	{
		count++;
		cout << "Singleton() begin\n" << endl;
		Sleep(1000);
		cout << "Singleton() end\n" << endl;
	}
private:
	//防止拷贝构造和赋值操作
	Singleton(const Singleton &obj) = delete;
	Singleton& operator=(const Singleton &obj) = delete;
public:
	static Singleton* getInstance()
	{
		// if (single == nullptr)
		// {
		// 	single = new Singleton();
		// 	cout << "new Singleton()"<< single << endl;
		// }
		return single;
	}

	static Singleton* releaseInstance()
	{
		if (single != NULL)
		{
			cout << "release\n" << endl;
			delete single;
			single = NULL;
		}
		return single;
	}
	void printS()
	{
		printf("Singleton printS test count:%d \n", count);
	}

private:
	static Singleton* single;
	static int count;
};

//note 静态变量类外初始化
Singleton* Singleton::single = new Singleton(); // nullptr;//
int Singleton::count = 0;
 

unsigned int threadfunc2(void *myIpAdd)
{
	int id = GetCurrentThreadId();
	printf("\n threadfunc%d \n", id);
	return id;
}

void threadFunc(void *myIpAdd)
{
	int id = GetCurrentThreadId();
	printf("\n threadFunc %d \n", id);
	Singleton::getInstance()->printS();
	return ;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int i = 0; 
	// DWORD dwThreadId[201];
	HANDLE hThread[201]; 
	int threadnum = 3;

	Singleton::getInstance()->printS();
	for (i = 0; i < threadnum; i++)
	{
		hThread[i] = (HANDLE)_beginthread(&threadFunc, 0, 0);

		if (hThread[i] == NULL)
		{
			printf("begin thread %d error!!!\n", i);
			break;
		}		
	}
	for (i = 0; i < threadnum; i++)
	{
		WaitForSingleObject(hThread[i], INFINITE);	  
	}
	printf("wait for thread finished\n");
	for (i = 0; i < threadnum; i++)
	{
		CloseHandle(hThread[i]);
	}
	Singleton::releaseInstance();
	cout <<"hello...."<<endl;
	system("pause");
	return 0;
}